<template>
	<view class="baseForm">
		<u-text text="出库目标" class="area-header">
		</u-text>
		<view class="body">
			<u--form labelPosition="left" :model="umodel" ref="uForm" class="form" labelWidth="200rpx"
			         errorType="toast">
			  <u-form-item label="工作中心" prop="workshopCode"  @click="openWorkCenterSelect">
			    <u--input v-model="umodel.workshopName" border="none" disabled disabledColor="#ffffff"
			              inputAlign="right" placeholder="请选择工作中心"></u--input>
			    <template #right>
			      <u-icon name="arrow-right"></u-icon>
			    </template>
			  </u-form-item>
			</u--form>
		</view>
		<!-- 条码录入 -->
		<view class="area-header">
			<u-text text="出库信息">
			</u-text>
			<u-text :text="'已扫 ' + scanList.length" align="right">
			</u-text>
		</view>
		<view class="upload-scan">
			<scan-bar id="scanStorageUnitInput" ref="scanBarRef" placeholder="扫描包装条码" @code-scanned="getStorageUnitInfoByCode"
				:key="datekey"></scan-bar>
		</view>
		<u-line></u-line>
		<view class="list-content">
			<view class="body">
				<u-list class="list" v-if="storageUnitDetailInfo && storageUnitDetailInfo.length > 0"
					:height="ListViewHeight">
					<u-list-item v-for="(detail, index) in storageUnitDetailInfo" :key="detail.id">
						<view class="card">
							<view class="right">
								<view class="title" style="word-break: break-all;">
									包装编码:&nbsp;&nbsp;{{detail.extenalCode}}
								</view>
								<view class="body">
									物料:&nbsp;&nbsp;{{ detail.materialCode }}-{{ detail.materialName }}
								</view>
								<view class="body">
									数量/重量:&nbsp;&nbsp;{{ detail.totalQuantity }}
								</view>
								<view class="body">
									单位:&nbsp;&nbsp;{{ detail.quantityUnit }}
								</view>
								<view class="body">
									存储批次:&nbsp;&nbsp;{{detail.stockBatch}}
								</view>
								<view class="body">
									供应批次:&nbsp;&nbsp;{{detail.supplyBatch}}
								</view>
								<view class="body">
									存储区:&nbsp;&nbsp;{{detail.storageSectionCode}}
								</view>
								<view class="body">
									货位:&nbsp;&nbsp;{{detail.binCode}}
								</view>
							</view>
							<view class="left" v-if="detail.isreceive === 1">
								<u-icon name="checkmark-circle-fill" color="#42b20e" size="30px"></u-icon>
								<u-icon name="close-circle-fill" color="#f56c6c" size="30px" @click="removeDetail(index)"></u-icon>
							</view>
						</view>
						<u-line></u-line>
					</u-list-item>
				</u-list>
				<!-- 空数据 -->
				<u-list v-else :height="ListViewHeight">
					<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
				</u-list>
			</view>
		</view>
		<u-line></u-line>
		
		<!-- 提交按钮 -->
		<view class="search">
			<u-button type="primary" @click="confirmButtonClick" class="custom-style" :loading="posting">出 库</u-button>
		</view>
		<u-picker :show="showWorkCenter" :columns="workCenters" keyName="workshopName" immediateChange
		          @cancel="showWorkCenter = false" @confirm="workCenterSelect"></u-picker>
		<u-modal :show="messageShow" :closeOnClickOverlay="false" title="提示" content="是否要删除此包装"
			:showCancelButton="true" @confirm="messageConfirm" @cancel="messageCancel"></u-modal>
		<u-modal :show="earlyMessageShow" :closeOnClickOverlay="false" title="提示" content="存在更早批次包装单位,确定依然出库吗？"
			:showCancelButton="true" @confirm="earlyConfirm" @cancel="earlyCancel"></u-modal>
	</view>
</template>

<script lang="ts" setup>
	import { computed, reactive, ref } from 'vue';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import ScanBar from '@/components/scan-bar/index.vue';
	import { http } from "../../../utils/http";
	import { useWmsStore } from '@/stores/useWmsStore';
	
	const props = defineProps({
		warehouseId: {
			type: String,
			default: '',
		},
		materialId: {
			type: String,
			default: '',
		}
	});

	// 重置表单信息 & 光标自动blur
	const scanBarRef = ref();
	const datekey = ref(new Date());
	const messageShow = ref(false);
	const deleteIndex = ref(0);
	const earlyMessageShow = ref(false);
	// 定义列表数据
	const scanList = ref([]);
	const showWorkCenter = ref(false);
	const ListViewHeight = ref(0);
	const workCenters = reactive([]);
	
	// 表单数据定义
	const umodel = reactive({
		workshopCode: '',
		workshopId: '',
		workshopName:'',
	});
	
	const storageUnitDetailInfo = computed(() => JSON.parse(useWmsStore().storageUnitDetailInfo));
	onShow(() => {
		ListViewHeight.value = uni.getSystemInfoSync().windowHeight - 230;
		console.log('ListViewHeight.value', ListViewHeight.value);
		getWorkCenter();
		reset();
	})
	
	onLoad(() => {
		setTimeout(()=>{
			scanBarRef.value.reset();
		}, 1000);
		
	})

	// 校验提交
	const uForm = ref();
	const posting = ref(false);
	
	async function getWorkCenter() {
	  const data = await http({
	  	url: '/mdm/mdmworkshop/getList',
	  	method: 'POST',
	  	data: {}
	  });
	  let list = data.data;
	  list.forEach(item=>{
	  	item.workshopName = `${item.workshopCode}-${item.workshopName}`
	  })
	  workCenters[0] = list;
	}
	
	async function openWorkCenterSelect() {
		showWorkCenter.value = true;
		uni.hideKeyboard();
	}
	
	function workCenterSelect(e) {
		if (e.value.length) {
		  umodel.workshopId = e.value[0].id;
		  umodel.workshopCode = e.value[0].workshopCode;
		  umodel.workshopName = e.value[0].workshopName;
		}
		showWorkCenter.value = false;
	}
	
	async function getStorageUnitInfoByCode(result : any) {
		console.log('扫码结果', result);
		const unitBarcode = result;
		let hasBarCode = false;
		// 在 details 数组中查找对应的数据
		for (let i = 0; i < storageUnitDetailInfo.value.length; i++) {
			if (unitBarcode == storageUnitDetailInfo.value[i].extenalCode) {
				storageUnitDetailInfo.value[i].isreceive = 1;
				hasBarCode = true;
				useWmsStore().setStorageUnitDetailInfo(storageUnitDetailInfo.value);
				const scannedStorageUnit = scanList.value.find(item => item.id === storageUnitDetailInfo.value[i].id);
				if (!scannedStorageUnit) {
					scanList.value.push(storageUnitDetailInfo.value[i]);
				}
				break;
			}
		}
		scanBarRef.value.reset();
		if (!hasBarCode) {
			uni.$u.toast('未找到对应包装！');
		}
		scanBarRef.value.reset();
		datekey.value= new Date();
	}

	function messageConfirm() {
		messageShow.value = false;
		storageUnitDetailInfo.value[deleteIndex.value].isreceive = 0;
		useWmsStore().setStorageUnitDetailInfo(storageUnitDetailInfo.value);
		let index = scanList.value.findIndex(item => item.id === storageUnitDetailInfo.value[deleteIndex.value].id);
		if (index == -1) {
			return;
		} else {
			scanList.value.splice(index, 1);
		}
	}
	
	function messageCancel() {
		messageShow.value = false;
	}
	
	function removeDetail(index : any) {
		deleteIndex.value = index;
		messageShow.value = true;
	}
	
	async function earlyConfirm() {
		earlyMessageShow.value = false;
		const data = await http({
			url: '/wms/warehousemove/outboundBatchForStock/',
			method: 'POST',
			data: {
				warehouseId: props.warehouseId,
				materialId: props.materialId,
				workshopCode: umodel.workshopCode,
				packingDetails: scanList.value,
			}
		});
		
		if(data.code == '200') {
			uni.$u.toast('出库成功');
			reset();
			uni.navigateBack({
				delta: 1, //返回层数，2则上上页
				success() {
					console.log("success");
					useWmsStore().setStorageUnitDetailInfo([]);
				},
			})
		};
	}
	
	function earlyCancel() {
		earlyMessageShow.value = false;
	}

	async function confirmButtonClick() {
		if (!umodel.workshopId) {
			uni.$u.toast('请选择要出库的工作中心！');
			return;
		}
		if (scanList.value.length == 0) {
			uni.$u.toast('请先扫描要出库的包装！');
		} else {
			let hasEarlyBatch = false;
			let stockBatchList = [];
			for (let i = 0; i < scanList.value.length; i++) {
				stockBatchList.push(storageUnitDetailInfo.value[i].stockBatch);
			}
			for (let i = 0; i < scanList.value.length; i++) {
				const stockBatch = stockBatchList.find(item => item === scanList.value[i].stockBatch);
				if (!stockBatch) {
					hasEarlyBatch = true;
					break;
				}
				
			}
			if (hasEarlyBatch) {
				earlyMessageShow.value = true;
			} else {
				const data = await http({
					url: '/wms/warehousemove/outboundBatchForStock/',
					method: 'POST',
					data: {
						warehouseId: props.warehouseId,
						materialId: props.materialId,
						workshopCode: umodel.workshopCode,
						packingDetails: scanList.value,
					}
				});
				
				if(data.code == '200') {
					uni.$u.toast('出库成功');
					reset();
					uni.navigateBack({
						delta: 1, //返回层数，2则上上页
						success() {
							console.log("success");
							useWmsStore().setStorageUnitDetailInfo([]);
						},
					})
				};
			}
		}
	}
	
	function reset() {
		scanList.value = [];
		umodel.workshopId = '';
		umodel.workshopCode = '';
	}
</script>

<style lang="scss">
	.baseForm {
		.area-header {
			color: #909193;
			padding: 6px 15px;
			margin-bottom: 0;
			font-size: 15px;
			background-color: #f3f4f6;
			display: flex;
		}

		.upload-scan {
			padding: 10px 20rpx;
		}

		.body {
			padding: $uni-page-padding;

			.scan-bar {
				display: flex;
				flex: 1;
			}
			.form {
				padding: 0 20rpx;
			}
		}
		
		.list-content {
			padding: $uni-page-padding;
		
			.list-title {
				line-height: 40px;
				font-size: 14px;
				color: rgba(0, 0, 0, 0.4);
			}
		
			.list {
				.card {
					// margin-top: 5px;
					// margin-bottom: 10px;
					border-radius: 7px;
					display: flex;
					align-items: center;
					padding: 10px 0;
					transition: all 300ms ease;
					box-shadow: 0 0 1px rgba(0, 0, 0, 0.1);
		
					.left {
						flex-basis: 120rpx;
						padding-right: 10px;
						text-align: right;
						font-size: 13px;
						display: flex;
						justify-content: space-between;
		
						.enter {
							line-height: 20px;
							margin-bottom: 5px;
						}
		
						.number {
							font-size: 13px;
							line-height: 18px;
						}
		
						:deep(.u-icon--right) {
							flex-direction: row-reverse;
						}
					}
		
					.right {
						flex: 1;
		
						.title {
							font-size: 15px;
							line-height: 20px;
							margin-bottom: 5px;
							font-weight: 700;
						}
		
						.body {
							padding-left: 0;
							font-size: 13px;
							line-height: 18px;
						}
					}
				}
			}
		}

		.search {
			display: flex;

			.custom-style {
				// width: 120px;
				margin: 10px 5px 5px;
				height: 36px;
				border-radius: 8px;

				&:nth-child(1) {
					flex: 1
				}

				&:nth-child(2) {
					flex: 3
				}
			}
		}
	}
</style>